# -*- coding:utf-8 -*-
"""
this classifier make use of the but word 却
the emotion after the but is usually the emotion to be emphisized
"""
import sys
import logging
import simplejson

from commontool.but_pattern import check_have_but_line,get_but_pos
from lyricemo.utils import get_emodict,get_c2wlist,split_by_emoword
from LyricStructure.pylyric.Lyric import Lyric

def predict_basic_sen(line):
    

def predict_1_que(lrc_str,print_line = False):
    # get the line with que and the emotion word around this word
    
    # check the emotion after and before the word
    # if strong emotion word after the 'but', then return the emotion
    # if not, return confidence 0 and unknown
    emo_dict = get_emodict()
    c2wlist = get_c2wlist()

    l = Lyric()
    l.loadstr(lrc_str)
    line_list = l.getlinelist()

    but_plus_pos = 0
    but_plus_neg = 0
    but_plus_none = 0

    for line_index,line_item in enumerate(line_list):
        line = line_item['content']
        but_count = check_have_but_line(line)
        if but_count == 0:
            continue

        #if print_line:
        #    print line
        if but_count > 1:
            #logging.error('more than two but for line %s'%(line))
            return(-1,1)
        
        but_pos = get_but_pos(line)
        if but_pos > 5:
            line_before = line[:but_pos]
            # TODO Get the len of the but pos 
            line_after = line[but_pos+1:]
        else:
            line_before = line_list[line_index-1]['content']
            line_after = line[but_pos+1:]

        # get emo after
        # get emo before

        # TODO : write the function for process common line
        split_line = split_by_emoword( line ,emo_dict,c2wlist)

        # get all the words after the but word
        tmp_count = 0
        for w_item in split_line:
            if not w_item.has_key('emo'):
                continue
            if w_item['start'] < but_pos:
                continue
            tmp_count += 1
            if w_item['emo'] > 0:
                if print_line:
                    print w_item['w']
                but_plus_pos += 1
            elif w_item['emo'] < 0:
                if print_line:
                    print w_item['w']
                but_plus_neg += 1
            #break
        if tmp_count == 0:
            but_plus_none += 1

    if but_plus_pos > but_plus_neg:
        return (1,but_plus_pos/ (but_plus_pos+but_plus_neg))
    elif but_plus_pos < but_plus_neg:
        return (-1,but_plus_neg/ (but_plus_pos+but_plus_neg))
    elif but_plus_pos ==  but_plus_neg:
        return (0,0)
    else:
        logging.error("%d,%d"%(but_plus_pos,but_plus_neg))
        raise Exception('why here')

"""
the following part is used for experiment
"""
def batch_run():
    from gdsettings import GD_DIR
    from commonprocess.read_ano import read_mid_p
    from pyweka.classifierresult import get_result_from_two_list,get_cm_from_two_list

    tr_mid_list = simplejson.load(open('%s/data/vote_split/train%d.json'%(GD_DIR,0)))
    te_mid_list = simplejson.load(open('%s/data/vote_split/test%d.json'%(GD_DIR,0)))
    mid_list = tr_mid_list+te_mid_list
    mid2p = read_mid_p()

    r_list = []
    p_list = []
    for mid in mid_list:
        lrc_str = open('/Users/wangxing/gd/lyrics/%s.lrc'%(mid)).read()
        l,c = predict_1_que(lrc_str.decode('gbk'))
        if c > 0:
            p_list.append( 1 if l>0 else 0)
            r_list.append(1 if mid2p[mid]>5 else 0)
            if p_list[-1] != r_list[-1]:
                print mid,p_list[-1],mid2p[mid]
                predict_1_que(lrc_str.decode('gbk'),True)
    rdic = get_result_from_two_list(r_list,p_list)
    cm = get_cm_from_two_list(r_list,p_list)
    print rdic,
    print cm


if __name__ == "__main__":
    # TODO add test to this package
    batch_run()
    exit()
    mid = sys.argv[1]
    lrc_str = open('/Users/wangxing/gd/lyrics/%s.lrc'%(mid)).read()
    print predict_1_que(lrc_str.decode('gbk'))
